#! /usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function

import os
import sys
import shutil
from argparse import ArgumentParser


def _copy_file(src, dest):
    shutil.copy2(src, dest)
    print("copy {} to {}".format(src, dest))


def _link(src, dest):
    os.symlink(src, dest)
    print("link {} to {}".format(src, dest))


def install(bindir=None, sheetdir=None, copy=False):
    userhome = os.getenv("HOME")
    currentdir = os.path.dirname(os.path.abspath(__file__))
    if not bindir:
        bindirs = [
            os.path.join(userhome, '.local/bin'),
            os.path.join(userhome, 'bin'),
            "/usr/local/bin",
            "/usr/bin",
        ]
        for _dir in bindirs:
            if os.path.exists(_dir):
                bindir = _dir
                break
        else:
            print("Error: There is no a valid bindir", file=sys.stderr)
            return 1
    if not sheetdir:
        user_local_dir = os.path.join(userhome, ".local")
        if os.path.exists(user_local_dir):
            sheetdir = os.path.join(user_local_dir, "cribsheets")
        else:
            sheetdir = os.path.join(userhome, ".cribsheets")
    source_bin_file = os.path.join(currentdir, 'crib.py')
    source_sheet_dir = os.path.join(currentdir, 'sheets')
    if copy:
        _copy_file(source_bin_file, os.path.join(bindir, "crib"))
        _copy_file(source_sheet_dir, sheetdir)
    else:
        _link(source_bin_file, os.path.join(bindir, "crib"))
        _link(source_sheet_dir, sheetdir)
    return 0


def main():
    parser = ArgumentParser()
    subparsers = parser.add_subparsers()

    parser_install = subparsers.add_parser(
        "install",
        help="安装命令便条与便条查看工具",
        description="安装默认为采用建立软连接的方式，如果要做拷贝，请指定 --copy 参数",
    )
    parser_install.add_argument("--bindir", help="指定安装查看工具的 bin 目录")
    parser_install.add_argument("--sheetdir", help="指定便条安装目录")
    parser_install.add_argument("--copy", action="store_true",
                                help="做拷贝，而不是做软链接")
    parser_install.set_defaults(func=install)
    args = parser.parse_args()
    ret = args.func(
        bindir=args.bindir,
        sheetdir=args.sheetdir,
        copy=args.copy
    )
    sys.exit(ret)


if __name__ == "__main__":
    main()
